package com.example.myshopping3.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.myshopping3.model.AliPay;
import com.example.myshopping3.model.Orders;
import com.example.myshopping3.service.OrderService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;

@Controller
@RequestMapping("/pay")
public class PayController {

    private String orderId;

    @Autowired
    private OrderService orderService;

    /**
     * 支付宝支付
     *
     * @return
     */
    @SneakyThrows
    @PostMapping("/aliPay")
    @ResponseBody
    public String aliPay(AliPay aliPay) {
//        this.orderId = aliPay.getOut_trade_no();
//        System.out.println(aliPay);
        this.orderId = aliPay.getOut_trade_no();
        System.out.println("接收到支付请求: " + aliPay);

        // 确保金额格式正确
        if (aliPay.getTotal_amount() != null) {
            // 转换为两位小数格式
            DecimalFormat df = new DecimalFormat("#.00");
            String formattedAmount = df.format(aliPay.getTotal_amount());
            aliPay.setTotal_amount(Double.parseDouble(formattedAmount));
        }
        //创建阿里支付的配置类对象
        AlipayConfig alipayConfig = new AlipayConfig();
        //设置网关地址
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        // 1. 转换金额为两位小数字符串
//        String totalAmount = String.format("%.2f",aliPay.getTotal_amount());
//
//        aliPay.setTotal_amount(totalAmount);

        //设置商家的Id
        alipayConfig.setAppId("9021000150685532");
        //设置应用私钥，该私钥是开发者使用秘钥工具生成的私钥
        alipayConfig.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCi9K0FESJ3b8e+raXjhN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NpdB7cPilX6/2UpxkP5ZkMLLSRI1rtqcnRUT19PjO5ZaYOzTG/IcHeFeNo32/DsncSt7aeL2lWki+Os6sTJdSidLmmVYbT8xjYZuwmETpmap1EftP1m9x58G4hjGXAoGBAKYTi3H66mFpKkxwkMNo4E86aPG8zAr7OnSgmXDir2CLW7oiQQgDYEGJ6VAvC4S27ETRk02ZMEyGbpDA/i43ulaIxM14GuSQE7DRkDBpI6oQ0CmiD5w9bsg1qmA0n7eUUOt52RUYykxZlfvagftbNQDjtZ7mV9epI3K5P7JgIbspAoGANEUJdpBxCp0ATzQCXLS7gva74ELfHqALbvpScE7SVDAA66t2MhERwBV2+Q0mHOdHwouwYzZ58XNvTanu5fAVHQb6RHc6ZSYH1qr7flegquhSbm6sqRn5ORnvJFr/mwv1pPKw3zaDijszc0IwDxcSQ6Rixxqaxx/aJYrNI/epIvA=");

        //设置请求数据的格式
        alipayConfig.setFormat("json");

        //设置编码集
        alipayConfig.setCharset("utf-8");
        //设置签名类型
        alipayConfig.setSignType("RSA2");
        //设置支付宝公钥
        alipayConfig.setAlipayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkjzKdFGRPRBRr223N1McFgU7Ak6Dulh0VwvMjT+Lk2aoU5M982QvUnX5s+kAFg9NZButTL7TxomGttFb3EVomBJQ6CrEOCerAmmiWeN2lU3pn5uMj9EwsZTB6ytotIXcqsfWfV37L42yJH61d8qPQqWnfPRIx3qPmhns5jy9SJpK5E2dqE8tbnj5Q83LJCzSvOgYVMM5EyQ76Z5uPpo/dvFs/tisXd6sD/PFrXBxpsNms/E1H51UIggxvW6Qh1UKDzU0sphAU7imDmjlFrVoNkm7uBJE7DGCYJAJ5SIAIM0kIwo0Cb3fGiyz6VCQsiN4FpXq843RVuCRR2Gz/03IrQIDAQAB");
        //使用aliPay的配置对象创建一个aliPay的客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

        //创建阿里支付的请求对象-基于网页支付的请求对象
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();

        //支付成功后要跳转的url地址-异步方式
        alipayTradePagePayRequest.setReturnUrl("http://localhost:8081/pay/success");

        //支付成功后要跳转的url地址-同步方式
        //alipayTradePagePayRequest.setNotifyUrl();
        //设置请求的业务数据,业务数据由我们自定义的业务数据Bean对象提供

        //aliPay要求传入的业务数据必须为JSON格式的字符串
        String aliPayJsonStr = JSONObject.toJSONString(aliPay);
        alipayTradePagePayRequest.setBizContent(aliPayJsonStr);



        //调用aliPay的支付接口，并将请求数据传入到支付接口中完成支付
        return alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
    }

    @GetMapping("/success")
    public String success() {
        System.out.println("222 = " + 222);
        //更新订单信息，将支付状态改为已支付
        orderService.update(new UpdateWrapper<Orders>().set("pay_status", 1).eq("order_id", orderId));
        return "/PaySuccess.html";
    }


}
